package cn.congine.wizarpos.mall.action;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.congine.wizarpos.mall.exception.MangoException;
import cn.congine.wizarpos.mall.model.open.CommonResultOutput;
import cn.congine.wizarpos.mall.model.open.MerchantDef;
import cn.congine.wizarpos.mall.model.open.MerchantDefQueryOutput;
import cn.congine.wizarpos.mall.model.open.MerchantdefSyncInput;
import cn.congine.wizarpos.mall.model.open.ProductVoucherDetailOutput;
import cn.congine.wizarpos.mall.model.open.ProductVoucherInput;
import cn.congine.wizarpos.mall.model.open.ProductVoucherOutput;
import cn.congine.wizarpos.mall.service.impl.WPosHttpClient;
import cn.congine.wizarpos.mall.service.impl.WizarposOpenRestClient;
import cn.congine.wizarpos.mall.utils.MatrixToImageWriter;
import cn.congine.wizarpos.mall.vo.ProductVoucher;

import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

@Controller
@RequestMapping(value = "/product_voucher")
public class ProductVoucherAction {
	private final Log log = LogFactory.getLog(getClass());

	@Autowired
	private WPosHttpClient wposHttpClient;
	
	@Autowired
	private WizarposOpenRestClient wizarposOpenRestClient;

	/**
	 * 获取提货券的详情
	 * 
	 * @param mid
	 * @param cardId
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "/product_voucher_info")
	public ModelAndView voucherInfo(
			@RequestParam(value = "mid") String mid,
			@RequestParam(value = "orderId") String orderId,
			HttpServletRequest httpRequest) {
		String cardId = (String) httpRequest.getSession().getAttribute("mrtCardId");
		if (StringUtils.isEmpty(cardId)) {//session过期，跳转到登录注册页面
			return new ModelAndView("forward:/vip/login");
		}
		
		ProductVoucherInput input = new ProductVoucherInput();
		input.setMid(mid);
		input.setCardId(cardId);
		input.setOrderId(orderId);
		ProductVoucherDetailOutput output = (ProductVoucherDetailOutput) wizarposOpenRestClient.post(input, "/wxshop/voucher/detail", ProductVoucherDetailOutput.class);
		Map<String, Object> data = new HashMap<String, Object>();

		MerchantdefSyncInput mrtInput = new MerchantdefSyncInput();
		mrtInput.setMid(mid);
		MerchantDefQueryOutput mrtOut = (MerchantDefQueryOutput) wizarposOpenRestClient.post(mrtInput, "/merchantdef/info", MerchantDefQueryOutput.class);		
		MerchantDef merchant = mrtOut.getResult();
		
		ProductVoucher wxOrder = output.getResult().getProductVoucher();
		data.put("wxOrder", wxOrder);
		data.put("merchant", merchant);
		data.put("mid", mid);
		return new ModelAndView("productvoucher/quan", data);
	}

	@RequestMapping(value = "/product_voucher_list")
	public ModelAndView voucherList(
			@RequestParam(value = "mid") String mid,
			HttpServletRequest httpRequest) {
		String cardId = (String) httpRequest.getSession().getAttribute("mrtCardId");
		if (StringUtils.isEmpty(cardId)) {//session过期，跳转到登录注册页面
			return new ModelAndView("forward:/vip/login");	
		}
		
		ProductVoucherInput input = new ProductVoucherInput();
		input.setMid(mid);
		input.setCardId(cardId);
		input.setPageNo("1");// 初始化取第一页的提货券
		ProductVoucherOutput output = (ProductVoucherOutput) wizarposOpenRestClient.post(input, "/wxshop/voucher/list", ProductVoucherOutput.class);
		
		List<ProductVoucher> list =(List<ProductVoucher>) output.getResult();
		
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("list", list);
		data.put("mid", mid);
		data.put("cardId", cardId);

		return new ModelAndView("productvoucher/quanlist", data);
	}

	/**
	 * 取对应页的提货券
	 * 
	 * @param openId
	 * @param mid
	 * @param nextPage
	 * @return
	 */
	@RequestMapping(value = "/next")
	public @ResponseBody List<ProductVoucher> next(
			@RequestParam(value = "mid") String mid,
			@RequestParam(value = "cardId") String cardId,
			@RequestParam(value = "nextPage", defaultValue = "1") Integer nextPage) {
		ProductVoucherInput input = new ProductVoucherInput();
		input.setMid(mid);
		input.setCardId(cardId);
		input.setPageNo(nextPage.toString());
		ProductVoucherOutput output = (ProductVoucherOutput) wizarposOpenRestClient.post(input, "/wxshop/voucher/list", ProductVoucherOutput.class);

		List<ProductVoucher> list = (List<ProductVoucher>) output.getResult();
		return list;
	}

	@RequestMapping(value = "/get_qrcode")
	@ResponseBody
	public void getQRcode(@RequestParam(value = "tokenId") String tokenId,
			HttpServletResponse response) {
		log.info("生成提货码>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
		if (tokenId == null || tokenId.isEmpty()) {
			log.error("tokenId is empty");
			return;
		}
		try {
			OutputStream stream = response.getOutputStream();
			MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
			Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
			hints.put(EncodeHintType.MARGIN, 1);
			hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
			BitMatrix bitMatrix = multiFormatWriter.encode(tokenId,
					BarcodeFormat.QR_CODE, 500, 500, hints);
			MatrixToImageWriter.writeToStream(bitMatrix, "png", stream);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (WriterException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取提货券二维码的令牌
	 * 
	 * @param orderId
	 * @param serviceCode
	 * @param mid
	 * @param signature
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws MangoException
	 */
	@RequestMapping(value = "/get_tokenId")
	@ResponseBody
	public String getTokenId(@RequestParam(value = "orderId") String orderId,
			@RequestParam(value = "serviceCode") String serviceCode,
			@RequestParam(value = "mid") String mid,
			@RequestParam(value = "signature") String signature)
			throws UnsupportedEncodingException, Exception {

		JSONObject data = new JSONObject();

		data.put("service_code", serviceCode);

		data.put("signature", signature);

		JSONObject json = new JSONObject();
		json.put("mid", mid);
		json.put("orderId", orderId);
		json.put("orderType", "1");

		data.put("param", json.toJSONString());

		JSONObject result = process(serviceCode, signature, json);

		if (result.containsKey("code") && result.getString("code").equals("0")) {
			return result.getJSONObject("result").getString("tokenId");
		}

		return "";
	}

	private JSONObject process(String serviceCode, String signature,
			JSONObject param) throws Exception {
		if (param == null || param.isEmpty())
			throw new MangoException("请求参数无效");
		JSONObject json = new JSONObject();
		json.put("service_code", serviceCode);
		json.put("signature", signature);
		json.put("param", param);
		return wposHttpClient.postCashier(json);
	}

}
